from bs4 import BeautifulSoup
import wx
import requests
import json


def getRiskArea():
    global req
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 '
                      'Safari/537.36 '
    }
    try:
        req = requests.get(url='https://ncov.dxy.cn/ncovh5/view/pneumonia_risks?from=dxy&link=&share=&source=',
                           headers=headers)
    except Exception:
        wx.MessageBox('网络连接失败')
        exit(1)
    req.encoding = 'utf8'
    html = req.text
    soup = BeautifulSoup(html, "html.parser")
    soup = soup.find('script', id='getAreaStat')
    data = str(soup)
    data = data.replace('<script id="getAreaStat">try { window.getAreaStat = ', '')

    data = data.replace('}catch(e){}</script>', '')
    return json.loads(data)


def show_risk(risk, level):
    if risk:
        risk_str = ''
        for item in risk:
            if item == risk[-1]:
                risk_str += item
            else:
                risk_str += f'{item}\n'
        return risk_str
    else:
        return f'没有{level}风险地区'


class RiskAreas(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        sampleList = ['显示所有地区', '只显示高风险地区', '只显示中风险地区']
        self.show_risk = wx.RadioBox(self, -1, "按照风险等级显示地区(不含港澳台)", (50, 25), wx.DefaultSize,
                                     sampleList, 3, wx.RA_SPECIFY_COLS | wx.NO_BORDER)
        self.refresh_button = wx.Button(self, label='刷新', pos=(500, 45), size=(100, 30))
        self.refresh_button.Bind(wx.EVT_BUTTON, self.onClickRefresh)
        self.high_result_label = wx.StaticText(self, label='高风险', pos=(50, 100))
        self.high_result_output = wx.TextCtrl(self, pos=(50, 120), size=(540, 100),
                                              style=wx.TE_MULTILINE | wx.TE_READONLY)
        self.mid_result_label = wx.StaticText(self, label='中风险', pos=(50, 230))
        self.mid_result_output = wx.TextCtrl(self, pos=(50, 250), size=(540, 160),
                                             style=wx.TE_MULTILINE | wx.TE_READONLY)

    def onClickRefresh(self, event):
        selection = self.show_risk.GetStringSelection()
        data = getRiskArea()
        high_risk = []
        high_risk_num = 0
        mid_risk_num = 0
        mid_risk = []
        for item_i in data:
            if item_i['dangerAreas']:
                for item_ii in item_i['dangerAreas']:
                    area = f"{item_i['provinceName']}-{item_ii['cityName']}_{item_ii['areaName']}"
                    if item_ii['dangerLevel'] == 1:
                        high_risk_num += 1
                        if high_risk_num < 10:
                            high_risk.append(f'00{high_risk_num}：{area}')
                        elif high_risk_num < 100:
                            high_risk.append(f'0{high_risk_num}：{area}')
                        else:
                            high_risk.append(f'{high_risk_num}：{area}')
                    elif item_ii['dangerLevel'] == 2:
                        mid_risk_num += 1
                        if mid_risk_num < 10:
                            mid_risk.append(f'00{mid_risk_num}：{area}')
                        elif mid_risk_num < 100:
                            mid_risk.append(f'0{mid_risk_num}：{area}')                        
                        else:
                            mid_risk.append(f'{mid_risk_num}：{area}')                        
        if selection == '只显示高风险地区':
            self.high_result_label.SetLabel(label=f'高风险地区：({high_risk_num}个)')
            self.mid_result_label.SetLabel(label='中风险')
            self.high_result_output.SetValue(show_risk(high_risk, '高'))
            self.mid_result_output.SetValue('')
        elif selection == '只显示中风险地区':
            self.high_result_label.SetLabel(label='高风险')
            self.mid_result_label.SetLabel(label=f'中风险地区：({mid_risk_num}个)')
            self.high_result_output.SetValue('')
            self.mid_result_output.SetValue(show_risk(mid_risk, '中'))
        else:
            self.high_result_label.SetLabel(label=f'高风险地区：({high_risk_num}个)')
            self.mid_result_label.SetLabel(label=f'中风险地区：({mid_risk_num}个)')
            self.high_result_output.SetValue(show_risk(high_risk, '高'))
            self.mid_result_output.SetValue(show_risk(mid_risk, '中'))
